<?php

class News extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Mnews');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->library('encrypt');
        $this->load->model('mmaster');
        $this->load->model('mglobal');
        $this->load->model('mterritory');
    }

    ########################################################################
    ########################################################################

    function index($proses="", $id="") {

        $data['template'] = "shell/smooth";
        $data['users'] = $this->mmaster->getUser();
        $data['main_view'] = 'ext-f-news';
        $data['proses'] = $proses;
        $data['id'] = $id;

        $data['data'] = array("news_header" => "", "news_content" => "", "territory_id" => "");
        if ($proses <> "" && $id <> "") {
            $getdata = $this->Mnews->selectById($id);
            foreach ($getdata as $r) {
                $data['data']['news_header'] = $r->news_header;
                $data['data']['news_content'] = $r->news_content;
                $data['data']['territory_id'] = $r->territory_id;
            }
        }
        #inisialisasi elemen form yang harus diisi
        $this->form_validation->set_rules('news_header', 'News Header', 'required');
        $this->form_validation->set_rules('news_content', 'News Content', 'required');
        $this->form_validation->set_rules('territory_id', 'Territory ID', 'required');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');

        if ($this->form_validation->run() != FALSE) {
            // masukkan data di sini
            $territoryIdList = $this->input->post("territory_id");
            $newsHeader = $this->input->post("news_header");
            $newsContent = $this->input->post("news_content");
            if ($proses == "add" && !empty($territoryIdList)) {
                for ($i = 0; $i < sizeof($territoryIdList); $i++) {
                    $territoryId = $territoryIdList[$i];
                    $this->Mnews->insert($territoryId, $newsHeader, $newsContent, $this->session->userdata("username"));
                }
            } else if ($proses == "update") {
                $territoryId = $this->input->post("territory_id");
                $this->Mnews->update($territoryId, $newsHeader, $newsContent, $this->session->userdata("username"), $id);
            }
            $this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
            redirect(base_url() . "index.php/news/");
        }

        $hasil = "";
        $this->load->view($data['template'], $data);
    }

    function territory_news_json() {

        echo($this->Mnews->getTerritoryTreeForNews());
//        echo($this->getTerritoryTreeForNews());
    }

    function getTerritoryTreeForNews($data=null, $id = 0, $p=0) {
//Donnie        
//Avoiding recursive lookup by generating sql by depth

        $selectSQL = "SELECT t1.territory_id AS lev1, t2.territory_id as lev2, t3.territory_id as lev3 " .
                "FROM t_mtr_territory AS t1 " .
                "LEFT JOIN t_mtr_territory AS t2 ON t2.parent_id = t1.territory_id " .
                "LEFT JOIN t_mtr_territory AS t3 ON t3.parent_id = t2.territory_id " .
                "WHERE t1.parent_id = 0 ORDER BY lev1,lev2,lev3";
        //echo $selectSQL . "<br/>";
        $selectById = "SELECT territory_id as id, parent_id FROM t_mtr_territory WHERE territory_id = ?";
        $list = $this->db->query($selectSQL, array());
        $list = $list->result();
        $data = array();
        for ($i = 0; $i < sizeof($list); $i++) {
            //echo $i . "<br/>";
            $level1 = $list[$i]->lev1;
            $level2 = $list[$i]->lev2;
            $level3 = $list[$i]->lev3;
            //echo "CHECKING $level1 $level2 $level3<br/>";
            $selectById = "SELECT territory_id as id, parent_id, territory_name as text, user_id, territory_type_id, istatus,ordering FROM t_mtr_territory WHERE territory_id = ?";
            $singleElement = $this->db->query($selectById, array($level1));
            $singleLev1 = $singleElement->result();
            if (empty($data[$level1])) {
                $data[$level1] = $singleLev1[0];
            }
            if (!empty($level2)) {
                $singleElement = $this->db->query($selectById, array($level2));
                $singleLev2 = $singleElement->result();
                if (empty($data[$level1]->children[$level2])) {
                    $data[$level1]->children[$level2] = $singleLev2[0];
                }
            }
            if (!empty($level3)) {
                $singleElement = $this->db->query($selectById, array($level3));
                $singleLev3 = $singleElement->result();
                if (empty($data[$level1]->children[$level2]->children[$level3])) {
                    $data[$level1]->children[$level2]->children[$level3] = $singleLev3[0];
                }
            }
        }
        //Normalize form
        $arrayLevel1 = array();
        $arrayLevel2 = array();
        $arrayLevel3 = array();

        foreach ($data as $id1 => $level1) {

            $arrayLevel2 = array();
            $arrayLevel3 = array();
//            array_push($arrayLevel1, $level1);
            if (isset($level1->children)) {

                // echo "Children level 1 detected<br/>";
                foreach ($level1->children as $id2 => $level2) {

                    if (isset($level2->children)) {
                        foreach ($level2->children as $id3 => $level3) {
                            array_push($arrayLevel3, $level3);
                        }

                        $level2->children = array();
                        //array_push($level2->children, $arrayLevel3);
                        $level2->children = $arrayLevel3;
                    }
                    array_push($arrayLevel2, $level2);
                }
                $level1->children = array();
                //array_push($level1->children, $arrayLevel2);
                $level1->children = $arrayLevel2;
            }
            array_push($arrayLevel1, $level1);
        }


//        echo "<pre>";
//        print_r($arrayLevel1);
//        echo "</pre>";
//
//        echo "<pre>";
//        // print_r($data);
//        echo "</pre>";
        return json_encode($arrayLevel1);
    }
    
    public function getByCreatedById_json($id) {
        if (isset($id)) {
            $data = $this->Mnews->selectByCreatedById($id);
            for ($i = 0; $i < sizeof($data); $i++) {
                $data[$i]->actions = "<a id=\"dialog_link\" href=\"" . base_url("index.php/news/index/update/" . $data[$i]->news_id) . "\">Update</a>";
            }
            echo json_encode($data);
        }
    }

}